package com.itheima.service;

import com.itheima.dao.OrderDao;
import com.itheima.dao.TxLogDao;
import com.itheima.domain.Order;
import com.itheima.domain.TxLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author MI
 * @ClassName OrderServiceImpl3.java
 * @createTime 2021年11月17日 22:38:00
 */
@Service
@Slf4j
public class OrderServiceImpl4 {
    @Resource
    private TxLogDao txLogDao;
    @Resource
    private OrderDao orderDao;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    //发送半事务性
    public void createOrderBefore(Order order) {
        String uid = UUID.randomUUID().toString().replace("-", "");
        //发送半事务消息
        rocketMQTemplate.sendMessageInTransaction("tx_producer_group",
                "tx_topic",
                MessageBuilder.withPayload(order).setHeader("txId", uid).build(),
                order
        );
    }

    @Transactional(rollbackFor = Exception.class)
    public void createOrder(String txId, Order order) {
        orderDao.save(order);
        TxLog txLog = new TxLog();
        txLog.setTxId(txId);
        txLogDao.save(txLog);
    }
}
